package com.cn.shuangzi.ad.manager;

import android.app.Activity;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.ad.ADBaseActivity;
import com.cn.shuangzi.ad.ADBaseFragment;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.KsErrorInfo;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.ADUtil;
import com.cn.shuangzi.ad.util.OnAdClosedListener;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.cn.shuangzi.ad.view.AlertRemoveAdDialog;
import com.cn.shuangzi.ad.view.AlertVipDialog;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.util.SZUtil;
import com.kwad.sdk.api.KsInterstitialAd;
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;

public class AdInterstitialFullManager {

    private TTFullScreenVideoAd mGMInterstitialFullAd;
    private ADBaseActivity adBaseActivity;
    private ADBaseFragment adBaseFragment;
    private Class<?> classBuyVip;
    private OnAdClosedListener onAdClosedListener;
    private AlertRemoveAdDialog.OnClickRemoveAdListener onClickRemoveAdListener;

    public AdInterstitialFullManager(ADBaseActivity adBaseActivity, AlertRemoveAdDialog.OnClickRemoveAdListener onClickRemoveAdListener) {
        this.adBaseActivity = adBaseActivity;
        this.onClickRemoveAdListener = onClickRemoveAdListener;
    }

    public AdInterstitialFullManager(ADBaseActivity adBaseActivity, Class<?> classBuyVip) {
        this(adBaseActivity, classBuyVip, null);
    }

    public AdInterstitialFullManager(ADBaseFragment adBaseFragment, AlertRemoveAdDialog.OnClickRemoveAdListener onClickRemoveAdListener) {
        this.adBaseFragment = adBaseFragment;
        this.onClickRemoveAdListener = onClickRemoveAdListener;
    }

    public AdInterstitialFullManager(ADBaseFragment adBaseFragment, Class<?> classBuyVip) {
        this(adBaseFragment, classBuyVip, null);
    }

    public AdInterstitialFullManager(ADBaseActivity adBaseActivity, Class<?> classBuyVip, OnAdClosedListener onAdClosedListener) {
        this.adBaseActivity = adBaseActivity;
        this.classBuyVip = classBuyVip;
        this.onAdClosedListener = onAdClosedListener;
    }

    public AdInterstitialFullManager(ADBaseFragment adBaseFragment, Class<?> classBuyVip, OnAdClosedListener onAdClosedListener) {
        this.adBaseFragment = adBaseFragment;
        this.classBuyVip = classBuyVip;
        this.onAdClosedListener = onAdClosedListener;
    }

    private Activity getActivity() {
        if (adBaseActivity != null) {
            return adBaseActivity;
        }
        if (adBaseFragment != null) {
            return adBaseFragment.getActivity();
        }
        return null;
    }

    public TTFullScreenVideoAd getGMInterstitialFullAd() {
        return mGMInterstitialFullAd;
    }


    private void loadAdReal(String unitId, String scenarioId) {
        if (getActivity() == null) {
            return;
        }
        ADManager.getInstance().clearCurrentInterstitial();
        TTAdNative adNativeLoader = TTAdManagerHolder.getInstance().createAdNative(getActivity());

        AdSlot adslot = new AdSlot.Builder()
                .setCodeId(unitId)
                .setOrientation(TTAdConstant.VERTICAL)
                .setMediationAdSlot(
                        new MediationAdSlot.Builder()
                                .setVolume(0)
                                .setMuted(true).setScenarioId(scenarioId)
                                .setAllowShowCloseBtn(true).build())
                .build();
        adNativeLoader.loadFullScreenVideoAd(adslot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                resetAdShowStatus();
                ADUtil.logError("展示显示失败：" + s);
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                mGMInterstitialFullAd = ttFullScreenVideoAd;
                showInterstitialFullAd();
            }

            @Override
            public void onFullScreenVideoCached() {

            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {
                mGMInterstitialFullAd = ttFullScreenVideoAd;
                showInterstitialFullAd();
            }
        });
    }

    public void loadAd(final String unitId, final String scenarioId) {

        if (!TTAdManagerHolder.isInitSuccess()) {
            ADManager.getInstance().addOnAdInitDoneListener(new ADManager.OnAdInitDoneListener() {
                @Override
                public void onTTAdInitDone(boolean isSuccess) {
                    ADManager.getInstance().removeOnAdInitDoneListener(this);
                    if (isSuccess) {
                        loadAdReal(unitId, scenarioId);
                    }
                }
            });
            ADManager.getInstance().initAd(true);
        } else {
            loadAdReal(unitId, scenarioId);
        }
    }

    private void resetAdShowStatus() {
        if (adBaseActivity != null) {
            adBaseActivity.setShownInteractionAd(false);
        } else if (adBaseFragment != null) {
            adBaseFragment.setShownInteractionAd(false);
        }
    }

    private void showInterstitialFullAd() {

        if (mGMInterstitialFullAd == null) {
            return;
        }
        mGMInterstitialFullAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
            @Override
            public void onAdShow() {
                try {
                    ADManager.getInstance().setGroMoreInteractionAdShownTime();
                    ADUtil.setShownInteractionAdWithRemoveAdPop();
                    ADUtil.setShownInteractionAd();
                    ADUtil.setShownInteractionAdByDays();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                MediationAdEcpmInfo gmAdEcpmInfo = mGMInterstitialFullAd.getMediationManager().getShowEcpm();
                ADUtil.logError("展示的插屏广告信息： adSdkName: " + gmAdEcpmInfo.getSdkName() + "   CustomSdkName：" + gmAdEcpmInfo.getCustomSdkName() + "   Ecpm: " + gmAdEcpmInfo.getEcpm());

                if (gmAdEcpmInfo != null) {
                    if (!ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getSdkName())) {
                        UnifiedInterstitialAD unifiedInterstitialAD = ADManager.getInstance().getYlhInterstitialAD();
                        YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getInterstitialYlhErrorInfo();
                        ADUtil.logError("ylhErrorInfo:" + ylhErrorInfo + "|unifiedInterstitialAD:" + unifiedInterstitialAD);
                        if (unifiedInterstitialAD != null && ylhErrorInfo != null) {
                            int ecpm = getReportEcmp(unifiedInterstitialAD.getECPM(), gmAdEcpmInfo.getEcpm());
                            unifiedInterstitialAD.sendLossNotification(ecpm, ylhErrorInfo.getReason(), ylhErrorInfo.getAdnId());
                            ADUtil.logError("上报优量汇插屏竞价失败：ecpm=" + ecpm + "，" + ylhErrorInfo);
                        }
                    }
                    if (!ADManager.getInstance().isKsPlatform(gmAdEcpmInfo.getSdkName())) {
                        KsInterstitialAd ksInterstitialAd = ADManager.getInstance().getKsInterstitialAD();
                        KsErrorInfo ksErrorInfo = ADManager.getInstance().getInterstitialKsErrorInfo();
                        ADUtil.logError("ksErrorInfo:" + ksErrorInfo + "|ksInterstitialAd:" + ksInterstitialAd);
                        if (ksErrorInfo != null && ksInterstitialAd != null) {
                            if (ksErrorInfo.getAdExposureFailedReason() != null) {
                                ksErrorInfo.getAdExposureFailedReason().setWinEcpm(getReportEcmp(ksInterstitialAd.getECPM(), gmAdEcpmInfo.getEcpm()))
                                        .setAdnName(ADManager.getInstance().getReportKsAdnName(gmAdEcpmInfo.getSdkName()));
                            }
                            ksInterstitialAd.reportAdExposureFailed(ksErrorInfo.getAdExposureFailureCode(), ksErrorInfo.getAdExposureFailedReason());
                            ADUtil.logError("上报快手插屏竞价失败：" + ksErrorInfo);
                        }
                    }
                }
            }

            @Override
            public void onAdVideoBarClick() {

            }

            @Override
            public void onAdClose() {
                resetAdShowStatus();
                if (onClickRemoveAdListener != null&& getActivity()!=null&&!getActivity().isFinishing()) {
                    new AlertRemoveAdDialog(getActivity(),onClickRemoveAdListener).show();
                    try {
                        SZManager.getInstance().onUMEvent(SZConst.EVENT_VIP_SHOW_CLOSE_INTERACTION_AD);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }
                if (classBuyVip != null&& getActivity()!=null && !getActivity().isFinishing()) {
                    new AlertVipDialog(getActivity(), classBuyVip).show();
                    try {
                        SZManager.getInstance().onUMEvent(SZConst.EVENT_VIP_SHOW_CLOSE_INTERACTION_AD);
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }
                if (onAdClosedListener != null) {
                    onAdClosedListener.onAdClosed();
                }
                destroy();
            }

            @Override
            public void onVideoComplete() {

            }

            @Override
            public void onSkippedVideo() {

            }
        });
        mGMInterstitialFullAd.showFullScreenVideoAd(getActivity());
    }

    private int getReportEcmp(int lossEcpm, String winEcpm) {
        int ecpm = lossEcpm;
        try {
            if (ecpm <= 0) {
                ecpm = 40 * ADConst.YUAN;
            }
            double preEcpm = Double.parseDouble(winEcpm);
            if (preEcpm > 0) {
                int addCPM = ADUtil.getRandom(5*ADConst.YUAN,3*ADConst.YUAN);
                ecpm = (int) (preEcpm + addCPM);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ecpm;
    }

    public void destroy() {
        if (mGMInterstitialFullAd != null) {
            mGMInterstitialFullAd.getMediationManager().destroy();
        }
//        adBaseActivity = null;
//        adBaseFragment = null;
        mGMInterstitialFullAd = null;
        ADManager.getInstance().clearCurrentInterstitial();
    }


}
